/**
 * 
 */
package com.doone.telmarket.service;

import java.io.ByteArrayInputStream;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import javax.xml.rpc.ServiceException;

import org.apache.log4j.Logger;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.doone.telmarket.domain.ServiceProduct;
import com.doone.telmarket.domain.ibator.ServiceHanding;
import com.doone.telmarket.infrastructure.dao.ServiceHandingDAO;
import com.doone.telmarket.infrastructure.dao.ServiceProductDAO;
import com.doone.telmarket.infrastructure.webservice.WSInterface;
import com.doone.telmarket.infrastructure.webservice.WSInterfaceLocator;
import com.doone.telmarket.infrastructure.xmlbeans.MessageBodyFactory;
import com.doone.telmarket.vo.ServiceOrderRelationResult;
import com.doone.telmarket.vo.ServiceOrderResult;

/**
 * @author 吴同庆
 * @date 2009-10-22
 * @description
 * @package com.doone.telmarket.service
 */
@Service("businessHandingService")
public class BusinessHandingServiceImp implements BusinessHandingService {

	private final static String ORDER_METHOD = "IFA_UserNwkUpdate";
	private final static String QUERY_METHOD = "IFA_IsmpQuery";

	private final static String ERROR_RESULT_CODE = "-1";
	private final static String SUCCESS_RESULT_CODE = "0";
	private final static String ERROR_MESSAGE = "目前系统资源忙，请稍候再试";

	private final static String ORDER_HANDING = "O";
	private final static String QUIT_ORDER_HANDING = "C";

	Logger log = Logger.getLogger(BusinessHandingServiceImp.class);

	@Autowired
	private MessageBodyFactory messageBodyFactory;

	@Autowired
	private ServiceHandingDAO serviceHandingDAO;

	@Autowired
	private ServiceProductDAO serviceProductDAO;

	public ServiceOrderResult order(String userId, String cityCode, String accNbr, String productId,
			String serviceOrderMode) {
		String requestXml = messageBodyFactory.orderMessage(cityCode, accNbr, productId, serviceOrderMode);
		WSInterface wsInterface = new WSInterfaceLocator();
		String reponseXml = "";
		ServiceOrderResult result = new ServiceOrderResult(ERROR_RESULT_CODE, ERROR_MESSAGE);
		try {
			reponseXml = wsInterface.getWSInterfacePort().webserviceIntfs(ORDER_METHOD, requestXml);
			result = messageBodyFactory.createServiceOrderResult(reponseXml);
			if (result.getResultCode().equals(SUCCESS_RESULT_CODE)) {
				Long key = saveServiceHanding(cityCode,userId, accNbr, productId, serviceOrderMode, ORDER_HANDING);
				log.info("增值业务订购记录保存：" + key);
			}

		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return result;
	}

	public List<com.doone.telmarket.vo.ValueAddedOrderRalation> queryOrderRelation(String cityCode, String accNbr, String serviceOrderMode) {
		String requestXml = messageBodyFactory.orderRelationMessage(cityCode, accNbr, serviceOrderMode);
		System.out.println("入参:"+requestXml);
		WSInterface wsInterface = new WSInterfaceLocator();
		String reponseXml = "";
		List<com.doone.telmarket.vo.ValueAddedOrderRalation> list = null;
		ServiceOrderRelationResult result = new ServiceOrderRelationResult(ERROR_RESULT_CODE, ERROR_MESSAGE);
		try {
			reponseXml = wsInterface.getWSInterfacePort().webserviceIntfs(QUERY_METHOD, requestXml);
			System.out.println("出参:"+reponseXml);
			list = this.parseXml(reponseXml);
//			result = messageBodyFactory.createServiceOrderRelationResult(reponseXml);
//			if (result.getProductIdCount() > 0) {
//				String queryParam = result.toQueryParame();
//				List<ServiceProduct> productList = serviceProductDAO.selectServiceProductByPrimaryKeyArray(queryParam);
//				result.addServiceProductList(productList);
//			}
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}

		return list;
	}

	public ServiceOrderResult quitOrder(String userId, String cityCode, String accNbr, String productId,
			String serviceOrderMode) {
		String requestXml = messageBodyFactory.quitOrderMessage(cityCode, accNbr, productId, serviceOrderMode);
		WSInterface wsInterface = new WSInterfaceLocator();
		String reponseXml = "";
		ServiceOrderResult result = new ServiceOrderResult(ERROR_RESULT_CODE, ERROR_MESSAGE);
		try {
			reponseXml = wsInterface.getWSInterfacePort().webserviceIntfs(ORDER_METHOD, requestXml);
			result = messageBodyFactory.createServiceOrderResult(reponseXml);
			if (result.getResultCode().equals(SUCCESS_RESULT_CODE)) {
				Long key = saveServiceHanding(cityCode,userId, accNbr, productId, serviceOrderMode, QUIT_ORDER_HANDING);
				log.info("增值业务退订记录保存：" + key);
			}
		} catch (RemoteException e) {
			e.printStackTrace();
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return result;
	}

	Long saveServiceHanding(String cityCode,String userId, String accNbr, String productId, String serviceOrderMode,
			String handingAction) {
		ServiceHanding handing = new ServiceHanding(cityCode,userId, accNbr, productId, serviceOrderMode, handingAction);
		Long key = serviceHandingDAO.insert(handing);
		return key;
	}
	
	@SuppressWarnings("unchecked")
	List<com.doone.telmarket.vo.ValueAddedOrderRalation> parseXml(String xml){
		try {
			xml = xml.replaceAll("lt;", "<");
			xml = xml.replaceAll("gt;", ">");
			xml = xml.replaceAll("&amp;", "");
			xml = xml.replaceAll("amp;", "");
			xml = xml.replaceAll("&", "");
			while(xml.indexOf("<?xml version=\"1.0\" encoding=\"GBK\"?>")!=-1){
				xml = xml.substring(0,xml.indexOf("<?xml version=\"1.0\" encoding=\"GBK\"?>"))+
				xml.substring(xml.indexOf("<?xml version=\"1.0\" encoding=\"GBK\"?>")+36,xml.length());
			}
			xml  =   "<?xml version=\"1.0\" encoding=\"GBK\"?>"+xml;
			SAXReader saxReader = new SAXReader();
			Document document = saxReader.read(new ByteArrayInputStream(xml.getBytes("GBK")));
			//System.out.println("***********"+document.asXML());
			List listId = document.selectNodes("/message/body/root/PHONEPACKAGEQUERY/SUBINFO/message/body/root/SUBINFO/PRODUCTINFO/message/body/root/PRODUCTINFO/PRODUCTID" );
			List listName = document.selectNodes("/message/body/root/PHONEPACKAGEQUERY/SUBINFO/message/body/root/SUBINFO/PRODUCTINFO/message/body/root/PRODUCTINFO/PRODUCTNAME_CN" );
			List spName = document.selectNodes("/message/body/root/PHONEPACKAGEQUERY/SUBINFO/message/body/root/SUBINFO/PRODUCTINFO/message/body/root/PRODUCTINFO/SPNAME_CN" );
			List priceList = document.selectNodes("/message/body/root/PHONEPACKAGEQUERY/SUBINFO/message/body/root/SUBINFO/PRODUCTINFO/message/body/root/PRODUCTINFO/CHARGINGPOLICY_CN");
			List<com.doone.telmarket.vo.ValueAddedOrderRalation> ralationList = new ArrayList<com.doone.telmarket.vo.ValueAddedOrderRalation>();
			for(int i=0;i<listId.size();i++){
				Element id=(Element)listId.get(i);   
				Element name=(Element)listName.get(i);
				Element sp_name=(Element)spName.get(i);
				Element price=(Element)priceList.get(i);
				com.doone.telmarket.vo.ValueAddedOrderRalation rala = new com.doone.telmarket.vo.ValueAddedOrderRalation();
				rala.setProductId(id.getText());
				rala.setProductName(name.getText());
				rala.setSpName(sp_name.getText());
				rala.setPrice(price.getText());
				ralationList.add(rala);
			}
			System.out.println("SIZE:"+ralationList.size());
			return ralationList;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		
	}

}
